﻿using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WeChat.UI.Model
{
    public abstract class ModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (!string.IsNullOrWhiteSpace(propertyName))
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected void SetValue<T>(ref T ralue, T value, Action? action = null, [CallerMemberName] string propertyName = "")
        {
            if (!Equals(ralue, value))
            {
                ralue = value;
                action?.Invoke();
                OnPropertyChanged(propertyName);
            }
        }

        #region
        readonly Lazy<ConcurrentDictionary<string, object>> _pairs = new Lazy<ConcurrentDictionary<string, object>>(true);

        protected T GetValue<T>(Func<T> func = null, [CallerMemberName] string propertyName = "")
        {
            object? val = _pairs.Value.GetOrAdd(propertyName, func == null ? default : func());
            return val == null ? (T)val : default;
        }

        protected void SetValue<T>(T value, Action action = null, [CallerMemberName] string propertyName = "")
        {
            if (_pairs.Value.TryAdd(propertyName, value))
            {
                action?.Invoke();
                OnPropertyChanged(propertyName);
            }
        }
        #endregion
    }
}
